<?php

/**
 * Description of Dmd_Controller_Plugin_Acl
 *
 * @author duc.do
 */
class Dmd_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract 
{
    private $_acl;

    public function __construct(Dmd_Acl $_acl) {
        $this->_acl = $_acl;
    }
    
    public function preDispatch(Zend_Controller_Request_Abstract $request) 
    {
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity()) {
            $request->setModuleName('front')
                    ->setControllerName('login')
                    ->setActionName('index')
                    ->setDispatched(false);
            return false;
        } else {
            $identity = $auth->getIdentity();
            if (method_exists($identity,"getRolesArray")) {
                $this->_acl->setRoles($identity->getRolesArray());
                $roles = $this->getRoleNameArray($identity->getRolesArray());
            } else {
                $roles = 'guest';
            }

            $resource = $request->getModuleName() . DS . $request->getControllerName();

            if (!$this->_acl->isAllowed($roles, $resource, $request->getActionName()))
            {
                $request->setModuleName('front')
                        ->setControllerName('error')
                        ->setActionName('error')
                        ->setDispatched(false);
                return false;
            }
        }
    }
    
    private function getRoleNameArray($rolesArray)
    {
        $arr = array();
        foreach ($rolesArray as $role)
        {
            $arr[] = $role['name'];
        }
        return $arr;
    }
}

?>
